import { Platform, Linking, Alert, } from 'react-native';
import { check, request, PERMISSIONS, RESULTS, requestMultiple, Permission, PermissionStatus } from 'react-native-permissions';



/**
 * 检查并请求位置 + 蓝牙权限
 * @returns {Promise<boolean>} 是否全部授权
 */
export const checkAndRequestLocationAndBluetoothPermissions = async (): Promise<boolean> => {
    try {
        // ---------- 1. 检查位置权限 ----------
        const locationPermissions = Platform.OS === 'ios'
            ? [PERMISSIONS.IOS.LOCATION_WHEN_IN_USE]
            : [PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION, PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION];

        for (const permission of locationPermissions) {
            const status = await check(permission);
            if (status !== RESULTS.GRANTED) {
                const result = await request(permission);
                if (result !== RESULTS.GRANTED) return false;
            }
        }

        // ---------- 2. 检查蓝牙权限（仅 Android） ----------
        if (Platform.OS === 'android') {
            // 强制权限：BLUETOOTH_CONNECT
            const connectStatus = await check(PERMISSIONS.ANDROID.BLUETOOTH_CONNECT);
            if (connectStatus !== RESULTS.GRANTED) {
                const result = await request(PERMISSIONS.ANDROID.BLUETOOTH_CONNECT);
                if (result !== RESULTS.GRANTED) return false;
            }

            // 可选权限：BLUETOOTH_SCAN，不影响返回结果
            const scanStatus = await check(PERMISSIONS.ANDROID.BLUETOOTH_SCAN);
            if (scanStatus !== RESULTS.GRANTED) await request(PERMISSIONS.ANDROID.BLUETOOTH_SCAN);
        }

        return true; // 所有必须权限都通过
    } catch (error) {
        console.error('Permission Error:', error);
        return false;
    }
};
/**
 * [ 检测蓝牙权限
 * @Author   ZQ
 */

export const checkAndRequestLocationPermissions = async () => {
    try {
        const permissions = Platform.OS === "ios"
            ? [PERMISSIONS.IOS.LOCATION_WHEN_IN_USE]
            : [
                PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
                PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION
            ];

        for (const permission of permissions) {
            const status = await check(permission);
            if (status === RESULTS.DENIED || status === RESULTS.BLOCKED) {
                const result = await request(permission);
                if (result !== RESULTS.GRANTED) {
                    return false;
                }
            } else if (status !== RESULTS.GRANTED) {
                return false;
            }
        }
        return true;
    } catch (error) {
        console.error("Location Permission Error: ", error);
        return false;
    }
};

/**
 * 检查并请求蓝牙权限（仅适用于 Android 12+，鸿蒙不执行）
 * @returns {Promise<boolean>} 是否成功获取蓝牙权限
 */
export const checkAndRequestBluetoothPermissions = async () => {
    if (Platform.OS == 'ios') {
        return true;
    }
    try {
        // 1. 先处理必须权限
        const connectPermission = PERMISSIONS.ANDROID.BLUETOOTH_CONNECT;
        const connectStatus = await check(connectPermission);
        if (connectStatus === RESULTS.DENIED || connectStatus === RESULTS.BLOCKED) {
            const result = await request(connectPermission);
            if (result !== RESULTS.GRANTED) return false;
        } else if (connectStatus !== RESULTS.GRANTED) {
            return false;
        }
        // 2. 尝试申请 SCAN 权限，但不强制要求
        const scanPermission = PERMISSIONS.ANDROID.BLUETOOTH_SCAN;
        const scanStatus = await check(scanPermission);

        if (scanStatus === RESULTS.DENIED || scanStatus === RESULTS.BLOCKED) {
            await request(scanPermission); // 不管结果
        }

        return true;
    } catch (error) {
        console.error("Bluetooth Permission Error: ", error);
        return false;
    }
};


/**
 * [ 检测苹果隐私权限--AppTrackingTransparency
 * @Author   ZQ
 */

// 处理 iOS 上请求“App Tracking Transparency”权限
export const CHECKIOSTRACKINGPERMISSION = async () => {
    const result = await check(PERMISSIONS.IOS.APP_TRACKING_TRANSPARENCY);
    if (result === RESULTS.DENIED) {
        await request(PERMISSIONS.IOS.APP_TRACKING_TRANSPARENCY);
    }
};



const PERMISSION_CAMERA =
    Platform.OS === "ios"
        ? [PERMISSIONS.IOS.PHOTO_LIBRARY]
        : [
            PERMISSIONS.ANDROID.CAMERA,

        ];

export async function usePhotoPermission(): Promise<boolean> {
    return new Promise((resolve, reject) => {
        requestMultiple(PERMISSION_CAMERA)
            .then((statuses) => {
                const check = PERMISSION_CAMERA.some((e) => statuses[e] === "granted");
                resolve(check);
            })
            .catch((err) => {
                resolve(false);
            });
    });
}


/**
 * 检查定位权限并处理定位服务
 * @param {Function} successCallback - 当权限授予时的回调
 * @param {Function} errorCallback - 当权限被拒绝时的回调
 */
export const checkLocationPermission = async (successCallback, errorCallback) => {
    try {
        const permissionStatus = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
        if (permissionStatus === RESULTS.GRANTED) {
            successCallback();
        } else {
            const permissionRequest = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
            if (permissionRequest === RESULTS.GRANTED) {
                successCallback();
            } else {
                if (errorCallback) errorCallback(new Error('Permission denied'));
            }
        }
    } catch (err) {
        if (errorCallback) errorCallback(err);
    }
};

/**
 * 打开设备的定位设置页面
 */
export const openLocationSettings = () => {
    Linking.openSettings().catch(() => {
        Alert.alert('无法打开设置', '请手动开启定位权限');
    });
};




// 定义权限类型
type PermissionType = 'camera' | 'microphone' | 'both';

// 定义权限结果类型
interface PermissionResult {
    hasPermission: boolean;
    status: Record<string, PermissionStatus>;
}

// 获取平台特定的权限常量
const getPermissions = (type: PermissionType): Permission[] => {
    const isIOS = Platform.OS === 'ios';

    const permissions: Permission[] = [];

    if (type === 'camera' || type === 'both') {
        permissions.push(isIOS ? PERMISSIONS.IOS.CAMERA : PERMISSIONS.ANDROID.CAMERA);
    }

    if (type === 'microphone' || type === 'both') {
        permissions.push(isIOS ? PERMISSIONS.IOS.MICROPHONE : PERMISSIONS.ANDROID.RECORD_AUDIO);
    }

    return permissions;
};

// 检查权限状态
export const checkPermissions = async (type: PermissionType = 'both'): Promise<PermissionResult> => {
    const permissions = getPermissions(type);
    const status: Record<string, PermissionStatus> = {};

    for (const permission of permissions) {
        status[permission] = await check(permission);
    }

    const hasPermission = Object.values(status).every(
        result => result === RESULTS.GRANTED
    );

    return { hasPermission, status };
};

// 请求权限
const requestPermissions = async (type: PermissionType = 'both'): Promise<PermissionResult> => {
    const permissions = getPermissions(type);
    const status: Record<string, PermissionStatus> = {};

    for (const permission of permissions) {
        status[permission] = await request(permission);
    }

    const hasPermission = Object.values(status).every(
        result => result === RESULTS.GRANTED
    );

    return { hasPermission, status };
};

// 检查并请求权限（如果未授予）
const checkAndRequestPermissions = async (type: PermissionType = 'both'): Promise<PermissionResult> => {
    // 先检查当前权限状态
    const { hasPermission, status } = await checkPermissions(type);

    // 如果已经有权限，直接返回
    if (hasPermission) {
        return { hasPermission: true, status };
    }

    // 否则请求权限
    return await requestPermissions(type);
};

// 处理被拒绝的权限（引导用户去设置）
const showPermissionDeniedAlert = (permissionNames: string[], onOpenSettings?: () => void) => {
    const permissionText = permissionNames.join(' 和 ');

    Alert.alert(
        '权限被拒绝',
        `需要 ${permissionText} 权限才能使用此功能。请前往设置中授予权限。`,
        [
            { text: '取消', style: 'cancel' },
            {
                text: '去设置', onPress: () => {
                    onOpenSettings ? onOpenSettings() : Linking.openSettings();
                }
            },
        ],
    );
};

// 综合权限检查与请求
export const handlePermissions = async (
    type: PermissionType = 'both',
    options?: {
        onGranted?: () => void;
        onDenied?: (status: Record<string, PermissionStatus>) => void;
        showAlert?: boolean;
    }
): Promise<boolean> => {
    try {
        // 👉 在 iOS 上直接放行
        if (Platform.OS === 'ios') {
            options?.onGranted?.();
            return true;
        }
        const { hasPermission, status } = await checkAndRequestPermissions(type);

        if (hasPermission) {
            options?.onGranted?.();
            return true;
        } else {
            options?.onDenied?.(status);
            if (options?.showAlert !== false) {
                const permissionNames = [];
                if (type === 'camera' || type === 'both') permissionNames.push('相机');
                if (type === 'microphone' || type === 'both') permissionNames.push('麦克风');
                showPermissionDeniedAlert(permissionNames);
            }
            return false;
        }
    } catch (error) {
        console.error('处理权限时出错:', error);
        return false;
    }
};
